<!-- 头条授权信息 toutiaoAuthorization  -->
<template>
  <view>
    <!-- 标题栏 -->
    <view class="head-box ss-m-b-60 ss-flex-col">
      <view class="ss-flex ss-m-b-20">
        <view class="head-title ss-m-r-40 head-title-animation">授权信息</view>
      </view>
      <view class="head-subtitle">完善您的头像、昵称、手机号</view>
    </view>

    <!-- 表单项 -->
    <uni-forms
      ref="accountLoginRef"
      v-model="state.model"
      :rules="state.rules"
      validateTrigger="bind"
      labelWidth="140"
      labelAlign="center"
    >
      <uni-forms-item name="avatar" label="头像">
        <view class="avatar-wrapper" data-eventsync="true" @tap="chooseAvatar">
          <image
            class="avatar-img"
            :src="sheep.$url.cdn(state.model.avatar)"
            mode="aspectFill"
          />
          <text class="cicon-forward" />
        </view>
      </uni-forms-item>
      <uni-forms-item name="avatar" label="手机号">
        <view class="avatar-wrapper" data-eventsync="true" open-type="getPhoneNumber" type="primary" bindgetphonenumber="getPhoneNumber">
          <uni-easyinput
            placeholder="请输入手机号"
            v-model="state.model.mobile"
            :inputBorder="false"
          />
        </view>
      </uni-forms-item>
      <uni-forms-item name="nickname" label="昵称">
        <uni-easyinput
          placeholder="请输入昵称"
          v-model="state.model.nickname"
          :inputBorder="false"
        />
      </uni-forms-item>
      <view class="foot-box">
        <button class="ss-reset-button authorization-btn" @tap="onConfirm"> 确认授权</button>
      </view>
    </uni-forms>
  </view>
</template>

<script setup>
  import { computed, ref, reactive } from 'vue';
  import sheep from '@/sheep';
  import { closeAuthModal } from '@/sheep/hooks/useModal';
  import FileApi from '@/sheep/api/infra/file';
  import UserApi from '@/sheep/api/member/user';
  import AuthUtil from '@/sheep/api/member/auth';

  const props = defineProps({
    agreeStatus: {
      type: Boolean,
      default: false,
    },
  });

  const userInfo = computed(() => sheep.$store('user').userInfo);

  const accountLoginRef = ref(null);

  // 数据
  const state = reactive({
    model: {
      nickname: userInfo.value.nickname,
      avatar: userInfo.value.avatar,
      sex: userInfo.value.avatar,
      mobile: userInfo.value.mobile,
    },
    rules: {},
    disabledStyle: {
      color: '#999',
      disableColor: '#fff',
    },
  });

  // 选择头像
  async function chooseAvatar() {
    try {
      tt.getUserProfile({
        success: (res) => {
          console.log('tt.getUserProfile success，获取的用户信息：', res);
          state.model.avatar = res.userInfo.avatarUrl;
          state.model.nickname = res.userInfo.nickName;
          state.model.sex = res.userInfo.gender;
          state.model.mobile = sheep.$platform.useProvider(provider).getPhoneNumber(res.encryptedData, res.rawData);
        },
        fail(err) {
          console.log('tt.getUserProfile failed', err.errMsg);

          tt.showModal({
            title: '获取用户信息失败',
            content: JSON.stringify(err),
            showCancel: false,
          });
        },
        complete() {
          console.log('tt.getUserProfile completed');
        },
      });
    } catch (e) {
      console.error('选择头像失败:', e);
    }
  }

  const getPhoneNumber = (e) => {
    console.log(e)
    if (e.detail.errMsg.slice(-2) === "ok") {
      console.log(
        "获取手机号的加密数据成功,开发者可以把该数据传回到自己的服务端进行解密获取手机号,加密数据为: ",
        e
      );
      // userInfo.mobile = sheep.$platform.useProvider('toutiao').getPhoneNumber(e.detail.encryptedData, '');

      tt.showToast({
        title: "success",
      });
    } else {
      console.log("获取手机号的加密数据失败: ", e);
      tt.showToast({
        title: "failed",
        icon: "none",
      });
    }
  };

  // 确认授权
  async function onConfirm() {
    const { model } = state;
    const { nickname, avatar } = model;
    if (!nickname) {
      sheep.$helper.toast('请输入昵称');
      return;
    }
    if (!avatar) {
      sheep.$helper.toast('请选择头像');
      return;
    }
    try {
      // 发起更新
      const { code } = await UserApi.updateUser({
        avatar: state.model.avatar,
        nickname: state.model.nickname,
      });
      // 更新成功
      if (code === 0) {
        sheep.$helper.toast('授权成功');
        await sheep.$store('user').getInfo();
        closeAuthModal();
      }
    } catch (e) {
      console.error('更新用户信息失败:', e);
      sheep.$helper.toast('更新失败，请重试');
    }
  }
</script>

<style lang="scss" scoped>
  @import '../index.scss';

  .foot-box {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .authorization-btn {
    width: 686rpx;
    height: 80rpx;
    background-color: var(--ui-BG-Main);
    border-radius: 40rpx;
    color: #fff;
  }

  .avatar-img {
    width: 72rpx;
    height: 72rpx;
    border-radius: 36rpx;
  }

  .cicon-forward {
    font-size: 30rpx;
    color: #595959;
  }

  .avatar-wrapper {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10rpx 0;
  }
</style>
